package com.netease.xone.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ViewFlipper;

/**
 * 添加onFlipperChange监听并允许自定义GestureDetector的ViewFlipper
 * 
 * @see ViewFlipper
 * @see GestureDetector
 */
public class MyViewFlipper extends ViewFlipper {
	GestureDetector mGestureDetector;

	public MyViewFlipper(Context context) {
		super(context);
	}

	public MyViewFlipper(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private OnFlipperChangeListener listener;

	public interface OnFlipperChangeListener {
		public void onFlipperChange(int index);
	}

	public void setOnFlipperChangeListener(OnFlipperChangeListener l) {
		listener = l;
	}

	public void setGestureDetector(GestureDetector gd) {
		mGestureDetector = gd;
	}

	@Override
	public void showNext() {
		if (getDisplayedChild() >= (getChildCount() - 1)) { // 最后一个了
			return;
		}

		super.showNext();

		if (listener != null)
			listener.onFlipperChange(getDisplayedChild());
	}

	@Override
	public void showPrevious() {
		if (getDisplayedChild() <= 0) { // 第一个了
			return;
		}
		super.showPrevious();

		if (listener != null)
			listener.onFlipperChange(getDisplayedChild());
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (mGestureDetector != null && mGestureDetector.onTouchEvent(ev)) {
			ev.setAction(MotionEvent.ACTION_CANCEL);
			super.dispatchTouchEvent(ev);
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}
}
